package com.example.androidlearning2200.adapter;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidlearning2200.bean.MsgBean;
import com.example.androidlearning2200.R;

import java.util.List;
import java.util.Random;

public abstract class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.RVHolder> {

    private List<MsgBean> datas;

    public MsgAdapter(List<MsgBean> msgBeans) {
        this.datas = msgBeans;
    }

    @NonNull
    @Override
    public RVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rv_we_chat, parent, false);
        return new RVHolder(view);
    }

    /**
     * 给每一个列表项填充内容
     *
     * @param holder   The ViewHolder which should be updated to represent the contents of the
     *                 item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     */
    @Override
    public void onBindViewHolder(@NonNull RVHolder holder, int position) {
        MsgBean msgBean = datas.get(position);
        holder.tvFlag.setText(msgBean.getName().substring(0, 1));
        Random random = new Random();
        holder.tvFlag.setBackgroundColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        holder.tvName.setText(msgBean.getName());
        holder.tvMsg.setText(msgBean.getMsg());
        holder.tvTime.setText(msgBean.getTime());
        holder.itemView.setOnClickListener(view -> clickItem(msgBean));
    }

    /**
     * 通过抽象方法对外暴露点击事件
     * 点击事件为抽象方法，自己无需实现，交由调用者实现
     * @param msgBean
     */
    public abstract void clickItem(MsgBean msgBean);

    @Override
    public int getItemCount() {
        return datas.size();
    }

    /**
     * 列表项包装器
     */
    public class RVHolder extends RecyclerView.ViewHolder {

        private TextView tvFlag;
        private TextView tvName;
        private TextView tvMsg;
        private TextView tvTime;

        public RVHolder(@NonNull View itemView) {
            super(itemView);
            tvFlag = itemView.findViewById(R.id.tvFlag);
            tvName = itemView.findViewById(R.id.tvName);
            tvMsg = itemView.findViewById(R.id.tvMsg);
            tvTime = itemView.findViewById(R.id.tvTime);
        }

    }

}
